using DocumentCreationSystem.Models;
using DocumentCreationSystem.Services;
using DocumentCreationSystem.Services.MCP;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;

namespace DocumentCreationSystem.Views
{
    /// <summary>
    /// Agent配置窗口
    /// </summary>
    public partial class AgentConfigWindow : Window, INotifyPropertyChanged
    {
        private readonly ILogger<AgentConfigWindow> _logger;
        private readonly IProjectToolsService _toolsService;
        private readonly IToolExecutionMonitor _toolExecutionMonitor;
        private readonly IAIService _aiService;
        private readonly ObservableCollection<ToolConfigViewModel> _tools = new();
        private AgentConfiguration _currentConfig = new();

        public event PropertyChangedEventHandler? PropertyChanged;

        public ObservableCollection<ToolConfigViewModel> Tools => _tools;

        public AgentConfigWindow(
            ILogger<AgentConfigWindow> logger,
            IProjectToolsService toolsService,
            IToolExecutionMonitor toolExecutionMonitor,
            IAIService aiService)
        {
            InitializeComponent();
            _logger = logger;
            _toolsService = toolsService;
            _toolExecutionMonitor = toolExecutionMonitor;
            _aiService = aiService;

            DataContext = this;
            ToolsDataGrid.ItemsSource = _tools;

            Loaded += OnLoaded;
            Closed += OnClosed;

            // 订阅配置更新事件
            ConfigurationNotificationService.AIModelConfigurationUpdated += OnAIModelConfigurationUpdated;
        }

        private async void OnLoaded(object sender, RoutedEventArgs e)
        {
            await LoadConfigurationAsync();
            await LoadCurrentAIModelInfoAsync();
            await LoadToolsAsync();
            await LoadStatisticsAsync();
        }

        private async Task LoadConfigurationAsync()
        {
            try
            {
                StatusTextBlock.Text = "正在加载配置...";

                // 加载默认配置
                _currentConfig = new AgentConfiguration
                {
                    Name = "DocumentCreationAgent",
                    Description = "文档创建专用AI助手",
                    Type = "文档创建专家",
                    ConfidenceThreshold = 0.7,
                    ModelProvider = "OpenAI",
                    ModelName = "gpt-4",
                    Temperature = 0.7,
                    EnableMemory = true,
                    MemoryRetentionDays = 30,
                    MaxMemoryItems = 10000,
                    AutoConsolidate = true,
                    EnableLearning = true,
                    LearningRate = 0.1,
                    LearnFromFailures = true,
                    MaxConcurrentTools = 3,
                    ToolTimeoutSeconds = 30
                };

                ApplyConfigurationToUI();
                StatusTextBlock.Text = "配置加载完成";
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "加载配置失败");
                StatusTextBlock.Text = "加载配置失败";
                MessageBox.Show($"加载配置失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void ApplyConfigurationToUI()
        {
            AgentNameTextBox.Text = _currentConfig.Name;
            AgentDescriptionTextBox.Text = _currentConfig.Description;
            AgentTypeComboBox.Text = _currentConfig.Type;
            ConfidenceThresholdSlider.Value = _currentConfig.ConfidenceThreshold;
            TemperatureSlider.Value = _currentConfig.Temperature;
            // 这些控件在XAML中未定义，暂时注释掉
            // EnableMemoryCheckBox.IsChecked = _currentConfig.EnableMemory;
            // MemoryRetentionSlider.Value = _currentConfig.MemoryRetentionDays;
            // MaxMemoryItemsTextBox.Text = _currentConfig.MaxMemoryItems.ToString();
            // AutoConsolidateCheckBox.IsChecked = _currentConfig.AutoConsolidate;
            // EnableLearningCheckBox.IsChecked = _currentConfig.EnableLearning;
            // LearningRateSlider.Value = _currentConfig.LearningRate;
            // LearnFromFailuresCheckBox.IsChecked = _currentConfig.LearnFromFailures;
            MaxConcurrentToolsTextBox.Text = _currentConfig.MaxConcurrentTools.ToString();
            ToolTimeoutTextBox.Text = _currentConfig.ToolTimeoutSeconds.ToString();
        }

        /// <summary>
        /// 加载当前AI模型信息
        /// </summary>
        private async Task LoadCurrentAIModelInfoAsync()
        {
            try
            {
                StatusTextBlock.Text = "正在加载AI模型信息...";

                if (_aiService is AIServiceManager aiServiceManager)
                {
                    // 获取当前提供商和模型信息
                    var currentProvider = aiServiceManager.GetCurrentProviderName();
                    var currentModel = aiServiceManager.GetCurrentModel();

                    // 更新UI显示
                    CurrentProviderText.Text = !string.IsNullOrEmpty(currentProvider) ? currentProvider : "未配置";
                    CurrentModelText.Text = currentModel?.Name ?? "未配置";

                    // 更新状态指示器
                    if (currentModel != null && currentModel.IsAvailable)
                    {
                        CurrentStatusText.Text = "已连接";
                        StatusIndicator.Fill = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Colors.Green);
                    }
                    else if (currentModel != null)
                    {
                        CurrentStatusText.Text = "已配置";
                        StatusIndicator.Fill = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Colors.Orange);
                    }
                    else
                    {
                        CurrentStatusText.Text = "未配置";
                        StatusIndicator.Fill = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Colors.Gray);
                    }

                    // 保存当前模型信息到Agent配置
                    if (currentModel != null)
                    {
                        _currentConfig.ModelProvider = currentProvider ?? "";
                        _currentConfig.ModelName = currentModel.Name ?? "";
                    }
                }
                else
                {
                    // 如果不是AIServiceManager，显示基本信息
                    CurrentProviderText.Text = "基础AI服务";
                    CurrentModelText.Text = "默认模型";
                    CurrentStatusText.Text = "未知";
                    StatusIndicator.Fill = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Colors.Gray);
                }

                StatusTextBlock.Text = "AI模型信息加载完成";
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "加载AI模型信息失败");
                StatusTextBlock.Text = "加载AI模型信息失败";

                // 设置错误状态
                CurrentProviderText.Text = "加载失败";
                CurrentModelText.Text = "加载失败";
                CurrentStatusText.Text = "错误";
                StatusIndicator.Fill = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Colors.Red);
            }
        }

        /// <summary>
        /// 打开AI模型配置窗口
        /// </summary>
        private async void OpenAIConfig_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                StatusTextBlock.Text = "正在打开AI模型配置...";

                // 获取主窗口实例
                var mainWindow = Application.Current.MainWindow as MainWindow;
                if (mainWindow != null)
                {
                    // 调用主窗口的AI模型配置方法
                    var aiConfigMethod = mainWindow.GetType().GetMethod("AIModelConfig_Click",
                        System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);

                    if (aiConfigMethod != null)
                    {
                        aiConfigMethod.Invoke(mainWindow, new object[] { sender, e });

                        // 等待配置窗口关闭后刷新模型信息
                        await Task.Delay(1000); // 给配置窗口时间打开
                        StatusTextBlock.Text = "AI模型配置窗口已打开，配置完成后将自动刷新";
                    }
                    else
                    {
                        _logger.LogError("无法找到AI模型配置方法");
                        StatusTextBlock.Text = "打开AI模型配置失败";
                        MessageBox.Show("无法打开AI模型配置窗口，请从主菜单访问。", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                    }
                }
                else
                {
                    _logger.LogError("无法获取主窗口实例");
                    StatusTextBlock.Text = "打开AI模型配置失败";
                    MessageBox.Show("无法打开AI模型配置窗口，请从主菜单访问。", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "打开AI模型配置失败");
                StatusTextBlock.Text = "打开AI模型配置失败";
                MessageBox.Show($"打开AI模型配置失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private async Task LoadToolsAsync()
        {
            try
            {
                StatusTextBlock.Text = "正在加载工具列表...";
                _tools.Clear();

                // 加载内置工具
                var builtInTools = await _toolsService.GetAvailableToolsAsync("All");
                foreach (var tool in builtInTools)
                {
                    _tools.Add(new ToolConfigViewModel
                    {
                        Name = tool.Name,
                        Category = tool.Category,
                        Description = tool.Description,
                        Version = "1.0.0",
                        IsEnabled = tool.IsEnabled,
                        IsBuiltIn = tool.IsBuiltIn
                    });
                }

                // MCP工具功能正在开发中

                StatusTextBlock.Text = $"已加载 {_tools.Count} 个工具";
                _logger.LogInformation($"已加载 {_tools.Count} 个工具");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "加载工具列表失败");
                StatusTextBlock.Text = "加载工具列表失败";
                MessageBox.Show($"加载工具列表失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private async Task LoadStatisticsAsync()
        {
            try
            {
                // 加载工具执行统计
                var allStats = _toolExecutionMonitor.GetAllStatistics();
                var totalCalls = allStats.Values.Sum(s => s.TotalExecutions);
                var successfulCalls = allStats.Values.Sum(s => s.SuccessfulExecutions);
                var avgResponseTime = allStats.Values.Any() 
                    ? allStats.Values.Average(s => s.AverageExecutionTime) 
                    : 0;

                // 这些控件在XAML中未定义，暂时注释掉
                // TotalCallsTextBlock.Text = totalCalls.ToString();
                // SuccessRateTextBlock.Text = totalCalls > 0 ? $"{(double)successfulCalls / totalCalls:P0}" : "0%";
                // AvgResponseTimeTextBlock.Text = $"{avgResponseTime:F0}ms";

                // MCP工具统计功能正在开发中
                
                // 模拟记忆统计（实际应该从记忆服务获取）
                // TotalMemoriesTextBlock.Text = "1,234";
                // AvgMemoryStrengthTextBlock.Text = "75%";
                // TotalAssociationsTextBlock.Text = "456";

                _logger.LogInformation("统计信息加载完成");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "加载统计信息失败");
            }
        }

        private async void SaveConfig_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                StatusTextBlock.Text = "正在保存配置...";

                // 从UI收集配置
                _currentConfig.Name = AgentNameTextBox.Text;
                _currentConfig.Description = AgentDescriptionTextBox.Text;
                _currentConfig.Type = AgentTypeComboBox.Text;
                _currentConfig.ConfidenceThreshold = ConfidenceThresholdSlider.Value;
                _currentConfig.Temperature = TemperatureSlider.Value;

                // 模型信息已经在LoadCurrentAIModelInfoAsync中设置，无需从UI读取
                // 这些控件在XAML中未定义，暂时注释掉
                // _currentConfig.EnableMemory = EnableMemoryCheckBox.IsChecked == true;
                // _currentConfig.MemoryRetentionDays = (int)MemoryRetentionSlider.Value;

                // if (int.TryParse(MaxMemoryItemsTextBox.Text, out var maxMemoryItems))
                //     _currentConfig.MaxMemoryItems = maxMemoryItems;

                // _currentConfig.AutoConsolidate = AutoConsolidateCheckBox.IsChecked == true;
                // _currentConfig.EnableLearning = EnableLearningCheckBox.IsChecked == true;
                // _currentConfig.LearningRate = LearningRateSlider.Value;
                // _currentConfig.LearnFromFailures = LearnFromFailuresCheckBox.IsChecked == true;
                
                if (int.TryParse(MaxConcurrentToolsTextBox.Text, out var maxConcurrentTools))
                    _currentConfig.MaxConcurrentTools = maxConcurrentTools;
                
                if (int.TryParse(ToolTimeoutTextBox.Text, out var toolTimeout))
                    _currentConfig.ToolTimeoutSeconds = toolTimeout;

                // 保存工具配置
                foreach (var tool in _tools)
                {
                    // 这里应该保存工具的启用状态
                    _logger.LogDebug($"工具 {tool.Name} 启用状态: {tool.IsEnabled}");
                }

                // 实际保存配置到文件或数据库
                await SaveConfigurationToFileAsync(_currentConfig);

                StatusTextBlock.Text = "配置保存成功";
                MessageBox.Show("配置保存成功", "信息", MessageBoxButton.OK, MessageBoxImage.Information);
                _logger.LogInformation("Agent配置保存成功");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "保存配置失败");
                StatusTextBlock.Text = "保存配置失败";
                MessageBox.Show($"保存配置失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private async Task SaveConfigurationToFileAsync(AgentConfiguration config)
        {
            var configPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), 
                "DocumentCreationSystem", "agent-config.json");
            
            var directory = Path.GetDirectoryName(configPath);
            if (!string.IsNullOrEmpty(directory) && !Directory.Exists(directory))
            {
                Directory.CreateDirectory(directory);
            }

            var json = System.Text.Json.JsonSerializer.Serialize(config, new System.Text.Json.JsonSerializerOptions { WriteIndented = true });
            await File.WriteAllTextAsync(configPath, json);
        }

        private async void MCPConfig_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                MessageBox.Show("MCP配置功能正在开发中...", "信息", MessageBoxButton.OK, MessageBoxImage.Information);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "打开MCP配置窗口失败");
                MessageBox.Show($"打开MCP配置窗口失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private async void RefreshTools_Click(object sender, RoutedEventArgs e)
        {
            await LoadToolsAsync();
        }

        private async void RefreshStats_Click(object sender, RoutedEventArgs e)
        {
            await LoadStatisticsAsync();
        }

        private void ConfigureTool_Click(object sender, RoutedEventArgs e)
        {
            if (sender is Button button && button.Tag is ToolConfigViewModel tool)
            {
                MessageBox.Show($"配置工具: {tool.Name}\n\n此功能正在开发中...", "工具配置", MessageBoxButton.OK, MessageBoxImage.Information);
            }
        }

        private async void ResetConfig_Click(object sender, RoutedEventArgs e)
        {
            var result = MessageBox.Show("确定要重置所有配置到默认值吗？", "确认重置", MessageBoxButton.YesNo, MessageBoxImage.Question);
            if (result == MessageBoxResult.Yes)
            {
                await LoadConfigurationAsync();
                StatusTextBlock.Text = "配置已重置";
            }
        }

        private void Close_Click(object sender, RoutedEventArgs e)
        {
            Close();
        }

        protected virtual void OnPropertyChanged(string propertyName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }

        /// <summary>
        /// 处理AI模型配置更新事件
        /// </summary>
        private async void OnAIModelConfigurationUpdated(object? sender, EventArgs e)
        {
            try
            {
                // 在UI线程中刷新模型信息
                await Dispatcher.InvokeAsync(async () =>
                {
                    await LoadCurrentAIModelInfoAsync();
                    _logger.LogInformation("Agent配置窗口已响应AI模型配置更新");
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "响应AI模型配置更新时发生错误");
            }
        }

        /// <summary>
        /// 窗口关闭时的清理
        /// </summary>
        private void OnClosed(object? sender, EventArgs e)
        {
            try
            {
                // 取消订阅事件
                ConfigurationNotificationService.AIModelConfigurationUpdated -= OnAIModelConfigurationUpdated;
                _logger.LogInformation("Agent配置窗口已清理事件订阅");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "清理Agent配置窗口事件订阅时发生错误");
            }
        }
    }

    /// <summary>
    /// 工具配置视图模型
    /// </summary>
    public class ToolConfigViewModel : INotifyPropertyChanged
    {
        private bool _isEnabled;

        public string Name { get; set; } = string.Empty;
        public string Category { get; set; } = string.Empty;
        public string Description { get; set; } = string.Empty;
        public string Version { get; set; } = string.Empty;
        public bool IsBuiltIn { get; set; }

        public bool IsEnabled
        {
            get => _isEnabled;
            set
            {
                _isEnabled = value;
                OnPropertyChanged(nameof(IsEnabled));
            }
        }

        public event PropertyChangedEventHandler? PropertyChanged;

        protected virtual void OnPropertyChanged(string propertyName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    /// <summary>
    /// Agent配置
    /// </summary>
    public class AgentConfiguration
    {
        public string Name { get; set; } = string.Empty;
        public string Description { get; set; } = string.Empty;
        public string Type { get; set; } = string.Empty;
        public double ConfidenceThreshold { get; set; } = 0.7;
        public string ModelProvider { get; set; } = string.Empty;
        public string ModelName { get; set; } = string.Empty;
        public string ApiKey { get; set; } = string.Empty;
        public double Temperature { get; set; } = 0.7;
        public bool EnableMemory { get; set; } = true;
        public int MemoryRetentionDays { get; set; } = 30;
        public int MaxMemoryItems { get; set; } = 10000;
        public bool AutoConsolidate { get; set; } = true;
        public bool EnableLearning { get; set; } = true;
        public double LearningRate { get; set; } = 0.1;
        public bool LearnFromFailures { get; set; } = true;
        public int MaxConcurrentTools { get; set; } = 3;
        public int ToolTimeoutSeconds { get; set; } = 30;
        public DateTime CreatedAt { get; set; } = DateTime.Now;
        public DateTime UpdatedAt { get; set; } = DateTime.Now;
    }
}
